package com.yunqi.autovender.activity;

import android.databinding.DataBindingUtil;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.google.gson.Gson;
import com.yunqi.autovender.R;
import com.yunqi.autovender.databinding.ActivityProductDetailBinding;
import com.yunqi.autovender.model.DrugInfo;
import com.yunqi.autovender.model.GlobalData;
import com.yunqi.autovender.view.ConfirmDialog;
import com.yunqi.autovender.view.PaymentDialog;
import com.yunqi.autovender.view.SelectPayTypeDialog;


import java.util.ArrayList;
import java.util.List;

import google.architecture.common.base.BaseActivity;
import google.architecture.common.util.ToastUtils;
import google.architecture.coremodel.callback.ConfirmCallback;
import google.architecture.coremodel.callback.ProductDetailClickCallback;
import google.architecture.coremodel.constant.ARGConstant;
import google.architecture.coremodel.constant.ARouterPath;
import google.architecture.coremodel.constant.ErrorCode;
import google.architecture.coremodel.constant.EventCode;
import google.architecture.coremodel.datamodel.http.entities.ProductData;
import google.architecture.coremodel.datamodel.http.entities.ShoppingCarItem;
import google.architecture.coremodel.helper.AppConfigHelper;
import google.architecture.coremodel.navigator.ProductDetailNavigator;
import google.architecture.coremodel.rx.RxEvent;
import google.architecture.coremodel.viewmodel.ProductDetailViewModel;

/**
 * 产品详情界面
 */
@Route(path = ARouterPath.ProductDetailAct)
public class ProductDetailActivity extends BaseActivity implements ProductDetailNavigator {

    private ActivityProductDetailBinding activityProductDetailBinding;
    private ProductData.Product product = null;
    private ProductDetailViewModel productDetailViewModel;
    private PaymentDialog mPaymentDialog;
    private ConfirmDialog mConfirmDialog;
    private AppConfigHelper mAppConfigHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activityProductDetailBinding = DataBindingUtil.setContentView(this, R.layout.activity_product_detail);
        if (savedInstanceState != null) {
            product = savedInstanceState.getParcelable(ARGConstant.ARG_PRODUCT);
        } else {
            product = getIntent().getParcelableExtra(ARGConstant.ARG_PRODUCT);
        }
        activityProductDetailBinding.txtDetails.setMovementMethod(ScrollingMovementMethod.getInstance());
        activityProductDetailBinding.setOnClick(mCallback);
        productDetailViewModel = new ProductDetailViewModel(this.getApplication());
        productDetailViewModel.setNavigator(this);
        productDetailViewModel.setProduct(product);
        activityProductDetailBinding.setProductDetailViewModel(productDetailViewModel);
        mAppConfigHelper = new AppConfigHelper(this);
        initRxBus();

//        showBack(activityProductDetailBinding.toolBar);
//        setTitle(activityProductDetailBinding.titleCenter, "商品详情");
    }


    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        super.onSaveInstanceState(outState, outPersistentState);
        outState.putParcelable(ARGConstant.ARG_PRODUCT, product);
    }

    @Override
    protected void onDestroy() {
        unSubscribeRxBus();
        super.onDestroy();
    }


    private ProductDetailClickCallback mCallback = new ProductDetailClickCallback() {
        @Override
        public void onBuy() {
            SelectPayTypeDialog selectPayTypeDialog = new SelectPayTypeDialog(ProductDetailActivity.this, new SelectPayTypeDialog.PayTypeCallback() {
                @Override
                public void onSelectPayType(int payType) {
                    String terNo = (String) GlobalData.getInstance().getData(ARGConstant.ARG_TERNO);
                    List<DrugInfo> dugInfoList = new ArrayList<>();
                    DrugInfo info = new DrugInfo();
                    info.setDrugName(product.getTitle());
                    info.setPlanId(product.getPlanId());
                    info.setDrugPrice(product.getPrice());
                    info.setQuantity(productDetailViewModel.count.get());
                    dugInfoList.add(info);
                    String drugInfos = new Gson().toJson(dugInfoList);
                    productDetailViewModel.creatTrade(terNo, payType, drugInfos);
                    double totalPrice = product.getPrice() * productDetailViewModel.count.get();
                    mPaymentDialog = new PaymentDialog(ProductDetailActivity.this, totalPrice);
                    mPaymentDialog.show();
                }
            });
            selectPayTypeDialog.show();


        }

        @Override
        public void onShoppingCar() {
            mConfirmDialog = new ConfirmDialog(ProductDetailActivity.this, new ConfirmCallback() {
                @Override
                public void onClick(int action) {
                    mConfirmDialog.dismiss();
                    if (action == ACTION_CONFIRM) {
                        productDetailViewModel.add2ShoppingCar(product, productDetailViewModel.count.get());
                    }
                }
            });
            mConfirmDialog.show();

        }

        @Override
        public void onJumpShoppingCar() {
            ARouter.getInstance()
                    .build(ARouterPath.ShoppingCarAct)
                    .withTransition(R.anim.activity_up_in, R.anim.activity_up_out)
                    .navigation(ProductDetailActivity.this);
            finish();
        }


        @Override
        public void onAdd() {
            int count = productDetailViewModel.count.get() + 1;
            int oldCount = productDetailViewModel.oldCount.get();
            productDetailViewModel.count.set(count);
            productDetailViewModel.reduceEnable.set(true);
            productDetailViewModel.addEnable.set((oldCount + count) < product.getDrugQuantity());

        }

        @Override
        public void onReduce() {
            int count = productDetailViewModel.count.get() - 1;
            productDetailViewModel.count.set(count);
            productDetailViewModel.reduceEnable.set(count > 1);
            productDetailViewModel.addEnable.set(true);
        }

        @Override
        public void onBack() {
            finish();
        }
    };

    @Override
    public void showImage(Bitmap bitmap) {
        mPaymentDialog.setQRCode(bitmap);
    }

    @Override
    public void onClearAllData(boolean isFinish) {
        Log.i(TAG, "Clear Shopping cart data success! ");
        if (isFinish) {
            finishAct();
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void onAddShopCar(ShoppingCarItem item) {
        ToastUtils.showShortToast(String.format(getString(R.string.tip_add_shopping_car_success), item.getTitle()));
    }

    @Override
    public void showError(int code, String errorMsg) {
        ToastUtils.showShortToast(errorMsg);
        switch (code) {
            case ErrorCode.FAILED_CREATE_ORDER:
            case ErrorCode.FAILED_CREATE_QRCODE:
                mPaymentDialog.hideLoading();
                break;
        }
    }

    @Override
    protected void onCall(RxEvent event) {
        switch (event.code) {
            case EventCode.PUSH_PAY_SUCCESS:
                if (mPaymentDialog != null && mPaymentDialog.isShowing()) {
                    mPaymentDialog.dismiss();
                }
                productDetailViewModel.clearShoppingCart();
                break;
        }
    }

    @Override
    protected void onCountDownFinished() {
        if (mAppConfigHelper.hasData()) {
            productDetailViewModel.clearShoppingCart();
        }
        else {
            finishAct();
        }
    }

    private void finishAct(){
        if(mConfirmDialog!=null&&mConfirmDialog.isShowing())
            mConfirmDialog.dismiss();
        if(mPaymentDialog!=null&&mPaymentDialog.isShowing())
            mPaymentDialog.dismiss();
        activityProductDetailBinding.txtBack.postDelayed(new Runnable() {
            @Override
            public void run() {
                finish();
            }
        },600);

    }

    @Override
    protected boolean isStartCountDown() {
        return true;
    }

}
